import { decodes } from "@/api/api";
import * as VueRouter  from "vue-router";
import {Store } from "vuex"
import {State} from "@/store/type"
export const configRouter = (router:VueRouter.Router, store:Store<State>) => {
  router.beforeEach(async (to:VueRouter.RouteLocationNormalized, from, next) => {
    const code = to.query.code;
    //如果有code ，则执行自动登录
    if (code) {
      try {
        const {
          data: {
            data:result
          },
        } = await decodes({ code: decodeURIComponent(code as string)});
        //登录
        if(result.token){
          store.dispatch("login", result.token);
        }
        //路由跳转
        to.name == "Login" ? next({ path: "/" }) : next();
      } catch (error) {
        console.log("error", error);
        to.name == "Login"
          ? next({ name: "Login" })
          : next({ name: "Login", query: { back: to.path } });
      }
    }
    //通用判断
    else {
      //需要登录判断
      if (to.name !== "Login" && !to.meta.notNeedLogin) {
        //没登录跳转登录页
        if (!store.state.isLogin) {
          next({ name: "Login", query: { back: to.path } });
        } else {
          //添加标签
          const item = store.state.menuTags.find((tag) => tag.path == to.path);
          if (!item) {
            store.commit("setMenuTags", {
              tag: {
                path: to.path,
                meta: to.meta,
                name: to.name,
              },
              method: "add",
            });
          }
          next();
        }
      } else {
        next();
      }
    }
  });
};
